package com.guass.nettyprotostuff.rpc.common;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public abstract class CommonHandler extends SimpleChannelInboundHandler<ModelMsg> {

    //记录次数
    private int heartbeatCount = 0;

    protected abstract void handlerData(ChannelHandlerContext ctx, ModelMsg msg);

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        IdleStateEvent stateEvent = (IdleStateEvent) evt;


        switch (stateEvent.state()) {
            case READER_IDLE:
                handlerReaderIdle(ctx);
                break;
            case WRITER_IDLE:
                handlerWriterIdle(ctx);
                break;
            case ALL_IDLE:
                handlerAllIdle(ctx);
                break;
            default:
                break;
        }
    }

    protected void sendPingMsg(ChannelHandlerContext ctx){

        ModelMsg hotKeyMsg = new ModelMsg();

        hotKeyMsg.setMessageType(TypeData.PING);

        ctx.channel().writeAndFlush(hotKeyMsg);
        heartbeatCount++;

    }

    protected void sendPongMsg(ChannelHandlerContext ctx) {

        ModelMsg hotKeyMsg = new ModelMsg();
        hotKeyMsg.setMessageType(TypeData.PONG);
        hotKeyMsg.setMsgId("guass server");

        ctx.channel().writeAndFlush(hotKeyMsg);

        heartbeatCount++;
    }

    protected void handlerAllIdle(ChannelHandlerContext ctx) {
    }

    protected void handlerWriterIdle(ChannelHandlerContext ctx) {
    }


    protected void handlerReaderIdle(ChannelHandlerContext ctx) {
    }
}
